<?php

namespace App\Imports;

use App\Models\ChapterQuestion;
use App\Models\LmSubject;
use App\Models\Papers;
use Illuminate\Support\Collection;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Shared\ZipArchive;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\Shared\Converter;

class ChapterImport
{
    public function joinFile($file, $column_id, $subject_id, $chapter_id)
    {
        //dd($file);
        $phpWord = IOFactory::load($file);
        //$phpWord->clearStyles();
        //$xmlWriter = IOFactory::createWriter($phpWord, "HTML");
        //$xmlWriter->save($_SERVER['DOCUMENT_ROOT']."/uploads/files/".time().".html");

        $S1 = $phpWord->getSections();
        //PaperTopic::wherePaperId($id)->delete();
        foreach ($S1 as $S) {
            $elements = $S->getElements();
            // 逐级读取／写入节点
            $arr = $this->copyElement($elements, $section, $column_id, $subject_id, $chapter_id);
        }
        return true;
    }

    /**
     * 逐级读取／写入节点
     *
     * @param Array
     *    需要读取的节点
     * @param PhpOffice\PhpWord\Element\Section
     *    节点的容器
     * @param Array
     *    文档2的所有节点
     */
    private function copyElement($elements, &$container, $column_id, $subject_id, $chapter_id)
    {
        $arrx = [];
        $par_id = 0;
        foreach ($elements as $k => $e1) {
            //dd($e1);
            $class = get_class($e1); //获取word中对应内容类型类
            $elname = explode("\\", $class)[3];
            //如果没找到分页 则默认为第一页
            if ($elname == 'PageBreak') {
                $this->currentPage++;
            } else {
                $this->currentPage = 1;
            }
            //文本节点 继续循环
            if ($elname == 'TextRun') {
                $arrx['tmptext'][] = $this->getTextElement($e1);//获取text节点内容
            } elseif ($elname == 'PreserveText') {
                $txt = $e1->getText();
                $arrt = [];
                foreach ($txt as $k => $v) {
                    $ar = htmlspecialchars_decode($v);
                    if (strpos($ar, 'INCLUDEPICTURE') !== false) { //包含图片
                        $txtarr = explode('"', $ar);
                        $ar = $this->getImage($txtarr[1]);
                    }
                    $arrt[$k] = $ar;
                }
                $new_txt = implode($arrt);
                //$txtarr = explode('"',htmlspecialchars_decode(implode('',$txt)));
                //$text = $txt[0]=='[' ? '['.$this->getImage($txtarr[1]): $this->getImage($txtarr[1]);
                $arrx['tmptext'][] = [['text' => $new_txt]];
            } elseif ($elname == 'TextBreak') {//换行下一题
                if (empty($arrx)) {
                    continue;
                }
                $arr = $this->parseArr($arrx);
                $new_arr = $value = [];
                $i = 0;
                $sort = 0;
                $type_id = 0;
                $topic_type = 0;
                $m_answer = [];
                $tName = "";
                $sele = "";
                $all = $testing = $content = $fen = $desc = $title = $answer = $image = '';
                foreach ($arr as $k => $v) {
                    if (strpos($v, '#材料分析题#') !== false) {
                        $title .= trim(trim(str_replace(['#材料分析题#'], '', $v), ' ')) . '<br/>';
                        $par_id = 0;
                        $type_id = 0;
                        $topic_type = 4;
                        $tName = "title";
                    } elseif (strpos($v, '#操作题#') !== false) {
                        $title .= trim(trim(str_replace(['#操作题#'], '', $v), ' ')) . '<br/>';
                        $par_id = 0;
                        $type_id = 0;
                        $topic_type = 5;
                        $tName = "title";
                    } elseif (strpos($v, '#写作题#') !== false) {
                        $title .= trim(trim(str_replace(['#写作题#'], '', $v), ' ')) . '<br/>';
                        $par_id = 0;
                        $type_id = 1;
                        $tName = "title";
                    } elseif (strpos($v, '#填空题#') !== false) {
                        $title .= trim(trim(str_replace(['#填空题#'], '', $v), ' ')) . '<br/>';
                        if ($par_id) {
                            $type_id = 3;
                        } else {
                            $par_id = 0;
                            $type_id = 2;
                        }
                        $tName = "title";
                    } elseif (strpos($v, '#简答题#') !== false) {
                        $title .= trim(trim(str_replace(['#简答题#'], '', $v), ' ')) . '<br/>';
                        $par_id = 0;
                        $type_id = 3;
                        $tName = "title";
                    } elseif (strpos($v, '#论述题#') !== false) {
                        $title .= trim(trim(str_replace(['#论述题#'], '', $v), ' ')) . '<br/>';
                        $par_id = 0;
                        $type_id = 4;
                        $tName = "title";
                    } elseif (strpos($v, '#活动设计题#') !== false) {
                        $title .= trim(trim(str_replace(['#活动设计题#'], '', $v), ' ')) . '<br/>';
                        $par_id = 0;
                        $type_id = 2;
                        $topic_type = 4;
                        $tName = "title";
                    } elseif (strpos($v, '#教学设计题#') !== false) {
                        $title .= trim(trim(str_replace(['#教学设计题#'], '', $v), ' ')) . '<br/>';
                        $par_id = 0;
                        $type_id = 1;
                        $topic_type = 4;
                        $tName = "title";
                    } elseif (strpos($v, '#辨析题#') !== false) {
                        $title .= trim(trim(str_replace(['#辨析题#'], '', $v), ' ')) . '<br/>';
                        $par_id = 0;
                        $type_id = 7;
                        $tName = "title";
                    } elseif (strpos($v, '#名词解释题#') !== false) {
                        $title .= trim(trim(str_replace(['#名词解释题#'], '', $v), ' ')) . '<br/>';
                        $par_id = 0;
                        $type_id = 8;
                        $tName = "title";
                    } elseif (strpos($v, '#翻译题#') !== false) {
                        $title .= trim(trim(str_replace(['#翻译题#'], '', $v), ' ')) . '<br/>';
                        $par_id = 0;
                        $type_id = 9;
                        $tName = "title";
                    } else {
                        if (preg_match("/^[a-zA-Z]/", $v) && $k != 0) {
                            $value[$i]['key'] = substr($v, 0, 1);
                            $value[$i]['value'] = html_entity_decode(substr($v, 2));
                            $i++;
                        } elseif (strpos($v, '正确答案') !== false) { //答案
                            $answer .= trim(trim(str_replace(['正确答案:', '正确答案：', '正确答案'], '', $v), ' '));
                            if (strlen($answer) > 6) {
                                $answer .= "<br />";
                            }
                            $tName = "answer";
                        } elseif (strpos($v, '试题解析') !== false) { //答案
                            $content .= trim(trim(str_replace(['试题解析:', '试题解析：'], '', $v), ' '));
                            $content .= "<br />";
                            $tName = "content";
                        } elseif (strpos($v, '试题分值') !== false) { //答案
                            $fen .= trim(trim(str_replace(['试题分值:', '试题分值：'], '', $v), ' '));
                        } elseif (strpos($v, '试题排序') !== false) { //答案
                            $sort = trim(trim(str_replace(['试题排序:', '试题排序：'], '', $v), ' '));
                        } elseif (strpos($v, '试题问题') !== false) {
                            $title = trim(trim(str_replace(['试题问题:', '试题问题：', '试题问题'], '', $v), ' '));
                            if ($topic_type != 4) {
                                $topic_type = 3;
                            }
                            //array_push($m_question, $sel);
                        } elseif (strpos($v, '试题答案') !== false) {
                            if ($sele) {
                                array_push($m_answer, $sele);
                            }
                            $sele = trim(trim(str_replace(['试题答案:', '试题答案：', '试题答案'], '', $v), ' '));
                            $tName = "sele";
                        } else {
                            //dd($v);
                            if ($tName == 'sele') {
                                $sele .= trim($v);
                                $sele .= "<br />";
                                if (($k + 1) == count($arr)) {
                                    array_push($m_answer, $sele);
                                }
                            } else if ($tName == 'title') {
                                $title .= trim($v);
                                $title .= "<br />";
                            } else if ($tName == 'content') {
                                $content .= trim($v);
                                $content .= "<br />";
                            } else if ($tName == 'answer') {
                                $answer .= trim($v);
                                $answer .= "<br />";
                            } else {
                                $title = trim($v);
                            }
                        }
                    }
                }
                //dd($title);
                //截取最后一个br
                $new_arr['answer'] = substr($answer, 0, 10) == '<br/>' ? substr($answer, 10) : $answer;
                $lenth = strlen($new_arr['answer']);
                if ($lenth == 1 && ctype_alnum($new_arr['answer'])) { //字母组合
                    if (count($value) == 2) {
                        $topic_type = 0;
                    } else {
                        $topic_type = 1;
                    }
                } elseif ($lenth > 1 && ctype_alnum($new_arr['answer']) && count($value) > 0) {
                    $topic_type = 2;
                } else {
                    if ($topic_type != 4) {
                        if ($type_id > 0 && $par_id == 0) {
                            $topic_type = 3;
                        }
                    }
                }
                $new_arr['column_id'] = $column_id;
                $new_arr['subject_id'] = $subject_id;
                $new_arr['chapter_id'] = $chapter_id;
                $new_arr['type'] = $topic_type;
                $new_arr['type_id'] = $type_id;
                $new_arr['par_id'] = $par_id;
                $new_arr['title'] = rtrim($title, '.');
                $new_arr['selectd'] = json_encode($value);
                $new_arr['content'] = html_entity_decode($content);
                $new_arr['sort'] = $sort;
                if (($topic_type == 4 && $par_id == 0) || ($topic_type == 5 && $par_id == 0)) {
                    $new_arr['content'] = $new_arr['title'];
                    $new_arr['title'] = "";
                }
                if ($par_id) {
                    $type = ChapterQuestion::where('id', $par_id)->value('type');
                    $new_arr['type_id'] = $new_arr['type'];
                    $new_arr['type'] = $type;
                }
                if ($new_arr['selectd'] == '[]' && $new_arr['type'] == 5 && ($new_arr['type_id'] == 2 || $new_arr['type_id'] == 1 || $new_arr['type_id'] == 0)) {
                    if ($new_arr['type'] != 4) {
                        $new_arr['type_id'] = 3;
                    }
                }
                //dd($new_arr);
                //插入数据
                $result = ChapterQuestion::create($new_arr);
                //dd($topic_type);
                if ($topic_type == 4 || $topic_type == 5) {
                    $par_id = $result->id;
                }
                $arrx = [];
            } elseif ($elname == 'Table') {
                $rows = count($e1->getRows()); //行数
                $cells = $e1->countColumns(); //列数
                //$style=$e->getStyle(); //表格样式
                //$width=$e->getWidth(); //宽度
                $arrx['rows'] = $rows;
                $arrx['cells'] = $cells;

                for ($i = 0; $i < $rows; $i++) {
                    $rows_a = $e1->getRows()[$i];
                    $arrx['height'][$i + 1] = $rows_a->getHeight();
                    //$arrx['rows'][$i+1]=$this->rowstyle($rows_a);
                    for ($j = 0; $j < $cells; $j++) {
                        //$arrx[$i][$r]=
                        $x = $rows_a->getCells()[$j];
                        $arrx['width'][$i + 1][$j + 1] = $x->getWidth();
                        $arrx['text'][$i + 1][$j + 1] = $this->getTextElement($x);
                        //$arrx['cells'][$i+1][$j+1]=$this->cellsstyle($x);
                    }
                }
            }
        }
        return $arrx;
    }

    /*
     * 处理数组
     */
    protected function parseArr($arrx)
    {
        $arr = [];
        foreach ($arrx['tmptext'] as $k => $qa) {
            $xas = '';
            if (is_array($qa)) {
                foreach ($qa as $axz) {
                    $xas .= $axz['text'];
                }
            }
            $arr[$k] = $xas;
        }
        return $arr;
    }

    /**
     * 获取Text节点
     */
    private function getTextElement($E)
    {
        $elements = $E->getElements();
        $xas = '';
        $result = [];
        $inResult = [];
        $text = [];
        foreach ($elements as $inE) {
            $ns = get_class($inE);
            $elName = explode('\\', $ns)[3];
            if ($elName == 'Text') {
                $result[] = $this->textarr($inE);
            } elseif ($elName == 'Image') {
                $result[] = $this->getImageElement($inE);
            } elseif (method_exists($inE, 'getElements')) {
                $inResult = $this->getTextElement($inE);
            }
            if (!is_null($inResult)) {
                $result = array_merge($result, $inResult);
            }
        }

        // if (count($result)>0) {
        //     foreach($result as $xaa) {
        //        var_dump($xaa);
        //     }
        // }


        return count($result) > 0 ? $result : null;
    }

    /**
     * 获取text的样式
     *
     * @param [type] $e
     * @return void
     */
    public function style($e)
    {
        $style = $e->getFontStyle();
        $arry = $style->getStyleValues();
        foreach ($arry as $key => $xas) {
            if (is_object($xas)) {
                $arry['Paragraph'][] = $xas->getStyleValues();
                unset($arry[$key]);

            }
        }

        return $arry;
    }

    /*
     * 生成本地图片
     */
    private function getImage($actualSource)
    {
        $img_name = createGuid() . '.png';
        $date = date('Ymd');
        $filePath = public_path("/uploads/images/" . $date . '/');
        if (!file_exists($filePath)) {
            mkdir($filePath, 755);
        }
        $local = "images/" . $date . "/" . $img_name;
        $content = file_get_contents($actualSource);
        if (file_put_contents($filePath . $img_name, $content)) {
            $app_url = config('app.url');
            return "<img src='$app_url/uploads/$local'/>";
        }
        return '';
    }

    /*
     * 获取图片内容
     */
    private function getImageElement($E)
    {
        $type = $E->getSourceType();
        $source = $E->getSource();
        if ($type == 'archive') {
            $source = substr($source, 6);
            list($zipFilename, $imageFilename) = explode('#', $source);

            $zip = new ZipArchive();
            if ($zip->open($zipFilename) !== false) {
                if ($zip->locateName($imageFilename) !== false) {
                    $isTemp = true;
                    $zip->extractTo(Settings::getTempDir(), $imageFilename);
                    $actualSource = Settings::getTempDir() . DIRECTORY_SEPARATOR . $imageFilename;
                }
            }
            $zip->close();
        } else {
            $actualSource = $source;
        }
        $img_name = createGuid() . '.png';
        $date = date('Ymd');
        $filePath = public_path("/uploads/images/" . $date . '/');
        if (!file_exists($filePath)) {
            mkdir($filePath, 755);
        }
        $local = "images/" . $date . "/" . $img_name;
        $content = file_get_contents($actualSource);
        if (file_put_contents($filePath . $img_name, $content)) {
            $app_url = config('app.url');
            return ['text' => "<img src='$app_url/uploads/$local'/>"];
        }
        return ['text' => ''];
    }

    /**
     * 行样式
     *
     * @param [type] $rows
     * @return void
     */
    public function rowstyle($rows)
    {
        $style = $rows->getStyle();

        $arry['TblHeader'] = $style->getTblHeader();
        $arry['CantSplit'] = $style->getCantSplit();
        $arry['ExactHeight'] = $style->getExactHeight();

        return $arry;

    }

    /**
     * 列的样式
     *
     * @param [type] $cells
     * @return void
     */
    public function cellsstyle($cells)
    {
        $style = $cells->getStyle();
        $arry['VAlign'] = $cells->getVAlign();
        $arry['TextDirection'] = $cells->getTextDirection();
        $arry['BgColor'] = $cells->getBgColor();
        $arry['GridSpan'] = $cells->getGridSpan();
        $arry['VMerge'] = $cells->getVMerge();
        $arry['Shading'] = $cells->getShading();
        $arry['Width'] = $cells->getWidth();
        $arry['Unit'] = $cells->getUnit();
        $arry['DefaultBorderColor'] = $cells->getDefaultBorderColor();

        return $arry;
    }

    public function textarr($e)
    {
        $textArr['text'] = $e->getText();
        //$textArr['style']=$this->style($e);

        return $textArr;
    }

}